package com.zxy.supplier_system.server.utils.wechat.official

import com.zxy.supplier_system.server.utils.wechat.validate200ErrorCodeAndMessageResponse
import org.springframework.core.ParameterizedTypeReference
import org.springframework.http.RequestEntity
import org.springframework.web.util.UriComponentsBuilder
import java.util.LinkedList


fun WechatOfficialAccountHelper.getFollowers(nextOpenId: String? = null): GetFollowersResponse {
    val accessToken = this.getOrFetchAccessToken()
    val builder =
        UriComponentsBuilder.fromUriString("https://api.weixin.qq.com/cgi-bin/user/get?access_token=$accessToken")
    if (nextOpenId != null) {
        builder.queryParam("next_openid", nextOpenId)
    }
    val requestEntity =
        RequestEntity.get(builder.build().toUriString()).build()
    val responseEntity = restTemplate.exchange(
        requestEntity,
        object : ParameterizedTypeReference<Map<String, Any>>() {},
    )
    return validate200ErrorCodeAndMessageResponse(responseEntity, GetFollowersResponse::class.java)
}

data class GetFollowersResponse(
    val total: Int,
    val count: Int,
    val data: Data?,
    val next_openid: String? = null
) {
    data class Data(
        val openid: List<String>
    )
}

fun WechatOfficialAccountHelper.getAllFollowers(): List<String> {
    val list = LinkedList<String>()
    var nextOpenId: String? = null
    do {
        nextOpenId = null
        val body = getFollowers()
        log.info("body:{} next_openid:{}", body, body.next_openid)
        nextOpenId = body.next_openid
        list.addAll(body.data?.openid ?: emptyList())
    } while (nextOpenId != null && nextOpenId.isNotBlank() && list.size < body.total)
    return list
}